package org.tinygroup.dbrouterjdbc3.sqlprocessor.pagedata;

import org.tinygroup.jsqlparser.extend.ParameterFinder.ParameterEntry;
import org.tinygroup.jsqlparser.statement.select.Fetch;
import org.tinygroup.jsqlparser.statement.select.Offset;
import org.tinygroup.jsqlparser.statement.select.PlainSelect;
import org.tinygroup.jsqlparser.statement.select.Select;
import org.tinygroup.jsqlparser.statement.select.SelectBody;

public class FetchPageDataProcess implements PageDataProcess {

	private ThreadLocal<Fetch> fetchlLocal=new ThreadLocal<Fetch>();
	private ThreadLocal<Offset> offsetLocal=new ThreadLocal<Offset>();
	
	public boolean isMatch(Select select) {
		SelectBody body = select.getSelectBody();
		if (body instanceof PlainSelect) {
			PlainSelect plainSelect = (PlainSelect) body;
			Fetch fetch = plainSelect.getFetch();
			Offset offset=plainSelect.getOffset();
			if (fetch != null&&offset!=null) {
				fetchlLocal.set(fetch);
				offsetLocal.set(offset);
				return true;
			}
		}
		return false;
	}

	public PageData buildPageData(Object[] values, ParameterEntry entry) {
		Fetch fetch=fetchlLocal.get();
		Offset offset=offsetLocal.get();
		if (fetch != null&&offset!=null) {
			PageData pageData=new PageData();
			Integer limitTemp = entry.getPositionMap().get("fetch");
			int limitIndex=-1;
			Long limitValue;
			if (limitTemp == null) {
				limitValue = fetch.getRowCount();
			} else {
				limitIndex = limitTemp;
				limitValue = Long
						.valueOf(
								String.valueOf(values[limitTemp
										.intValue() - 1])).longValue();
			}
			pageData.setLimitIndex(limitIndex);
			pageData.setLimitValue(limitValue);
			int startIndex=-1;
			Long startValue;
			Integer startTemp = entry.getPositionMap().get("offset");
			if (startTemp == null) {
				startValue = offset.getOffset();
			} else {
				startIndex = startTemp;
				startValue = Long
						.valueOf(
								String.valueOf(values[startTemp
										.intValue() - 1])).longValue();
			}
			pageData.setStartIndex(startIndex);
			pageData.setStartValue(startValue);
			return pageData;
		}
		return null;
	}

}
